package com.lenovo.spider.process.exceptions;

import com.lenovo.spider.process.TaskProcess;
import com.lenovo.spider.domain.Task;

import java.util.function.Predicate;

/**
 * @author <a href="mailto:liuhan3@lenovo.com">HanL(liuhan3)</a>
 * on 2018/3/22 10:18
 */
public abstract class ExceptionHandler implements TaskProcess {

    public Task handle(Task task) {
        return doIf(not(Task::isSuccess), t -> {
            handle(task.getCause());
            return t;
        }).apply(task);
    }

    private Predicate<Task> not(Predicate<Task> predicate) {
        return t -> !predicate.test(t);
    }

    /**
     * 支持的异常类型
     *
     * @param throwable
     * @return
     */
    abstract boolean support(Throwable throwable);

    /**
     * 处理该异常
     *
     * @param throwable
     * @return
     */
    abstract boolean handle(Throwable throwable);

    /**
     * 处理器顺序，order越小，越早处理
     *
     * @return
     */
    abstract int getOrder();
}
